package com.mmall.service.impl;

import com.google.common.collect.Lists;
import com.mmall.service.IFileService;
import com.mmall.utils.FtpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by chenxu on 17/7/28.
 */
@Service("iFileService")
public class FileServiceImpl implements IFileService{
    Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    public String upload(MultipartFile file,String path){

        String fileName = file.getOriginalFilename();

        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        String uploadFileName = UUID.randomUUID().toString()+"."+fileExtension;
        logger.info("start to upload");

        File fileDir = new File(path);
        if (!fileDir.exists()){
            fileDir.setWritable(true);
            fileDir.mkdir();
        }

        File targetFile =new File(path, uploadFileName);
        try {
            file.transferTo(targetFile);
            // start to upload ftp
            FtpUtil.uploadFile(Lists.newArrayList(targetFile));
            // after completed, delete uploaded file
            targetFile.delete();
        } catch (IOException e) {
            logger.error("file upload fail", e);
            return null;
        }
        return targetFile.getName();
    }
}
